/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package piccat.model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class provides static methods for the creation of new games. Usually
 * this involves loading the game from a game.properties file.
 * 
 * @author Hamish Morgan
 */
public class GameFactory {

    private final static String GAME_FILE = "data/game.properties";
//    private static final Random RAND = new Random();

    private GameFactory() {
    }

    public static Map<String, String> getGameNames() throws GameLoadException {
        Properties props = getPropertiesFile();
        String[] games = loadGameNames(props);

        Map<String, String> gamemap = new HashMap<String, String>();
        for (String game : games) {
            final String name = props.getProperty(game + ".name");
            gamemap.put(name, game);
        }

        return gamemap;
    }

    public static Game makeMultiGame(int numPlayers, String key) throws
            GameLoadException {
        Properties props = getPropertiesFile();
        Game gm = loadMultiGame(props, key, numPlayers);
        return gm;
    }

    private static Properties getPropertiesFile() throws GameLoadException {
        try {
            final Properties props = new Properties();
            InputStream is = new FileInputStream(GAME_FILE);
            props.load(is);
            return props;
        } catch (FileNotFoundException ex) {
            throw new GameLoadException(
                    "The game configuration file (" + GAME_FILE +
                    ") was not found.", ex);
        } catch (IOException ex) {
            throw new GameLoadException(
                    "The game configuration file (" + GAME_FILE +
                    ") could not be read from.", ex);
        }
    }

    private static String[] loadGameNames(Properties props) throws
            GameLoadException {
        return loadList(props, "games", "\\s*,\\s*");
    }

    private static Game loadMultiGame(Properties props, String game,
            int numPlayers) throws
            GameLoadException {

        final String[] sets = loadList(props, game + ".sets", "\\s*,\\s*");

        final int rows = loadInt(props, game + ".rows");

        final int cols = loadInt(props, game + ".cols");

        final boolean checkCompleteness = loadBoolean(props, game +
                ".checkCompleteness");

        final boolean checkMatching = loadBoolean(props, game +
                ".checkMatching");

        final boolean checkValidity = loadBoolean(props, game +
                ".checkValidity");

        final Random rand = new Random();
        String order = props.getProperty(game + ".order");
        if(order == null)
            order = "ascending";
        order = order.trim().toLowerCase();
        final boolean random = order.matches("^ra?nd.*$");
        final boolean descending = order.matches("^desc.*$");

        if(random && order.matches("^.*[\\d]+.*$")) {
            String[] parts = order.split("\\s");
            long seed = Long.parseLong(parts[1]);
            rand.setSeed(seed);
        }

        final List<List<Picture>> pictureSets = new ArrayList<List<Picture>>();
        for (String set : sets) {
            List<URL> imageUrls = loadPictureSet(props, set);
            if (imageUrls.size() < rows) {
                throw new GameLoadException(
                        "The number of pictures is set " + set +
                        " is less that the number of rows");
            }
            List<Picture> thisSet = new ArrayList<Picture>();
            for (int i = 0; i < rows; i++) {

                final URL url;
                if(random) {
                    int index = rand.nextInt(imageUrls.size());
                    url = imageUrls.remove(index);
                } else {
                    url = imageUrls.get(i);
                }
                thisSet.add(new Picture(url, set));
            }
            pictureSets.add(thisSet);
        }

        final List<Picture> pictures = new ArrayList<Picture>();
        
        for(int i = 0; i < rows; i++) {
            for(int  j =0; j < sets.length; j ++) {
                pictures.add(pictureSets.get(j).get(i));
            }
        }

        if(descending) {
            Collections.reverse(pictures);
        } else if(random) {
            Collections.shuffle(pictures, rand);
        }

//
//
//        for (String set : sets) {
//            List<URL> imageUrls = loadPictureSet(props, set);
//            if (imageUrls.size() < rows) {
//                throw new GameLoadException(
//                        "The number of pictures is set " + set +
//                        " is less that the number of rows");
//            }
//
//            if (order.equals("descending")) {
//                for (int i = rows - 1; i >= 0; i--) {
//                    URL url = imageUrls.get(i);
//                    pictures.add(new Picture(url, set));
//                }
//            } else if (order.equals("random")) {
//                for (int i = 0; i < rows; i++) {
//                    URL url = imageUrls.remove(RAND.nextInt(imageUrls.size()));
//                    pictures.add(new Picture(url, set));
//                }
//            } else {
//                for (int i = 0; i < rows; i++) {
//                    URL url = imageUrls.get(i);
//                    pictures.add(new Picture(url, set));
//                }
//            }
//
//        }
//
//        if (order.equals("descending")) {
//            Collections.reverse(pictures);
//        } else if (order.equals("random")) {
//            Collections.shuffle(pictures);
//        }

        System.out.println(order);

        Game result = new Game(numPlayers, rows, cols);
        result.setCheckCompleteness(checkCompleteness);
        result.setCheckMatching(checkMatching);
        result.setCheckValidity(checkValidity);
        result.addAllPictures(pictures);

        return result;
    }

    private static List<URL> loadPictureSet(Properties props, String set) {
        String tmp = props.getProperty(set + ".size");
        final int size = Integer.parseInt(tmp);
        final List<URL> urls = new ArrayList<URL>();
        for (int i = 0; i < size; i++) {
            final String key = set + ".image[" + i + "]";
            final String val = props.getProperty(key);

            String prefix = "";
            if (!val.matches("^[\\w]{3,}:.*$")) {
                prefix = "file:";
            }
            try {
                urls.add(new URL(prefix + val));
            } catch (MalformedURLException ex) {
                Logger.getLogger(GameFactory.class.getName()).
                        log(Level.SEVERE, null, ex);
            }
        }
        return urls;
    }

    private static String[] loadList(Properties props, String key,
            String delim) throws GameLoadException {
        if (!props.containsKey(key))
            throw new GameLoadException("The key " + key + " doest not exist.");
        String tmp = props.getProperty(key);
        String games[] = tmp.trim().split(delim);
        return games;
    }

    private static int loadInt(Properties props, String key) throws
            GameLoadException {
        if (!props.containsKey(key))
            throw new GameLoadException("The key " + key + " doest not exist.");
        String str = props.getProperty(key);
        int value = Integer.parseInt(str);
        return value;
    }

    private static boolean loadBoolean(Properties props, String key) throws
            GameLoadException {
        if (!props.containsKey(key))
            throw new GameLoadException("The key " + key + " doest not exist.");
        String tmp = props.getProperty(key);
        tmp = tmp.trim().toLowerCase();
        if (tmp.matches("^(true|1|yes)$"))
            return true;
        else if (tmp.matches("^(false|0|no)$"))
            return false;
        return false;
    }
}
